package fr.toto.subtitles;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.file.Path;
import java.util.Properties;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.kokotchy.betaSeriesAPI.model.Episode;
import com.kokotchy.betaSeriesAPI.model.Show;
import com.kokotchy.betaSeriesAPI.model.SubtitleLanguage;

import fr.toto.constantes.Constantes;
import fr.toto.exceptions.ProcessException;
import fr.toto.triseries.BetaSeriesQuery;
import fr.toto.triseries.EpisodesSet;
import fr.toto.triseries.Regex;
import fr.toto.triseries.Reglages;
import fr.toto.triseries.SeriesSet;

public class DldSoutitre implements Runnable , Constantes {

	private static Properties seriesFile = Reglages.initSeriesFile();
	private static Pattern pat = Pattern.compile(Regex.SERIE + Regex.SUBTITLEFILE);
	private Path file;
	private Path filename;
	private Soutitre s;
	private Episode ep;
	private SubtitleLanguage lang;

	public DldSoutitre(Path file) {
		this.file = file;
		this.filename = file.getFileName();
	}

	@Override
	public void run() {
		if (!analyseFile())
			return;
		
		s = SoutitreSet.extraitSoutitre(ep.getShowUrl(), ep.getSeason(), ep.getEpisode(), lang);
		if(s == null) {
			s = new Soutitre(ep,lang,"");
			try {
				s.move(file,ep);
			} catch (IOException e) {
				return;
			}
		} else {
			try {
			s.move(file,ep);
			}catch (Exception e) {
				SoutitreSet.add(s);
			} finally {
				SoutitreSet.Save();
			}
		}
		
	}
	
	public boolean analyseFile() {

		Matcher m = pat.matcher(filename.toString());
		if (!m.matches())
			return false;
		String serie = m.group(1).replace(".", " ").replace("_", " ").trim();
		String url = findUrl(serie);
		if(url.equalsIgnoreCase(""))
			return false;
		int season = Integer.parseInt(m.group(2));
		int episode = Integer.parseInt(m.group(3));
		lang = SubtitleLanguage.UNKNOWN;
		String reste = m.group(4);
		if(Regex.EnglishPattern.matcher(reste).find()) {
			lang = SubtitleLanguage.VO;
		}
		if(Regex.FrenchPattern.matcher(reste).find()) {
			if(lang == SubtitleLanguage.VO)
				return false;
			lang = SubtitleLanguage.VF;
		}
		if(lang == SubtitleLanguage.UNKNOWN)
			return false;
		
		ep = EpisodesSet.find(url, season, episode);
		if (ep == null) {
			ep = BetaSeriesQuery.getEpisode(url, season, episode);
			if (ep == null) 
				return false;
			EpisodesSet.add(ep);
		}		
		return true;

	}
	
	private String findUrl(String serie) {

		// Recherche dans fichier Series
		String url = seriesFile.getProperty(serie.toLowerCase(), "null");

		// SI pas trouvé :
		if (url.equals("null")) {
			
			url = SeriesSet.searchUrl(serie);
			if (url.isEmpty()) {
				// - Recherche sur site
				Set<Show> shows = BetaSeriesQuery.search(serie.replaceAll(
						Regex.SHOWNAME, " ").trim());
				Show show = Regex.getBestUrl(shows, serie, 0);
				if (show != null)
					url = show.getUrl();
			}
			// - si pas trouvé message Erreur
			if (url.isEmpty())
				System.err.println("impossible de trouver la série : " + serie);
			//TODO

			// - ajout dans fichier (avec url vide si pas trouvé)
			seriesFile.setProperty(serie.toLowerCase(), url);
			try {
				seriesFile.store(new OutputStreamWriter(new FileOutputStream(
						LISTSHOWPATH.toString()), CharsetName),
						MESSAGES.getString("serieFileExplanation"));
			} catch (Exception e) {
				new ProcessException(e);
			}
		}
		return url;
	}

}
